<template>
    <div>
        <div class="clearfix">
            <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
                <a-button> <a-icon type="upload" /> {{name}} </a-button>
            </a-upload>
            <a-button
                type="primary"
                :disabled="fileList.length === 0"
                :loading="uploading"
                style="margin-top: 16px"
                @click="handleUpload"
                >
                {{ uploading ? '上传中' : '开始上传' }}
            </a-button>
        </div>
    </div>
</template>
<script>
import axios from "axios"
export default {
    name:"attachFile",
    props:{name:String},
    data() {
        return {
            fileList: [],
            uploading: false,
        };
    },
    methods:{
        handleRemove(file) {
            const index = this.fileList.indexOf(file);
            const newFileList = this.fileList.slice();
            newFileList.splice(index, 1);
            this.fileList = newFileList;
        },
        beforeUpload(file) {
            this.fileList = [...this.fileList, file];
            return false;
        },
        handleUpload() {
            const { fileList } = this;
            const formData = new FormData();
            fileList.forEach(file => {
                formData.append('files[]', file);
            });
            this.uploading = true;
            // You can use any AJAX library you like
            axios.post(window.g.apiUrl+'manage/upload',formData).then(res=>{
                this.fileList = []
                this.uploading = false
                if(res.data.code==200){
                    this.$message.success(res.data.message);
                    this.$emit('returnFileUrl',res.data)
                }else{
                    this.$message.error(res.data.message);
                }
            }).catch(()=>{
                this.uploading = false
                this.$message.error('上传失败');
            });
        },
    }
}
</script>